<?php
require_once("Model/ModelsInclude.php");

/*
 * Istanza generica per accesso ad attributi del model.
 */
$c = Cliente::getInstance();

/*
 * Connessione DB.
 */
$db = new DatabaseManager();
$db->Connect();

?>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<link href="css/admin.css" rel="stylesheet" type="text/css" />
        <title>Admin</title>
    </head>
    <body>
		<?php
		$modelToInstanziate = $_GET["ModelName"];
		$formToPopulate = $_GET["FormName"];
		$fieldToPopulate = $_GET["FieldId"];
		$fieldLabelToPopulate = $fieldToPopulate."_label";
		$optionalFields = isset($_GET["OptionalFields"]) ? $_GET["OptionalFields"] : NULL;
		$conditionParam = isset($_GET["ConditionParam"]) ? $_GET["ConditionParam"] : NULL;
		$conditionValue = isset($_GET["ConditionValue"]) ? $_GET["ConditionValue"] : NULL;
		if($modelToInstanziate == "" || $fieldToPopulate == "" || !class_exists($modelToInstanziate))
		{
			echo("<p style=\"color:#f00;\"><b>Parametri della richiesta non validi!</b></p>");
		}
		else
		{
			$fieldLabelToPopulate = $fieldToPopulate."_label";
			$c = new $modelToInstanziate();
			$objsList = NULL;
			if($conditionParam != NULL && $conditionValue != NULL && isset($c->attribIsNumeric[$conditionParam]))
			{
				$cond = "";
				$conditionValue = mysql_real_escape_string($conditionValue);
				if($c->attribIsNumeric[$conditionParam])
					$cond = DatabaseManager::EncodeFieldName($conditionParam)." = ".$conditionValue;
				else
					$cond = DatabaseManager::EncodeFieldName($conditionParam)." = '".$conditionValue."'";
				$objsList = $c->getListFromDB($db,NULL,NULL,"",$cond);
			}
			else
				$objsList = $c->getListFromDB($db,NULL,NULL,"");
			?>

<script language="javascript" type="text/javascript">

var formToPopulateName = <?= "'".$formToPopulate."'" ?>;
var fieldToPopulateName = <?= "'".$fieldToPopulate."'" ?>;
var fieldToPopulateLabelName = <?= "'".$fieldLabelToPopulate."'" ?>;
var optionalfieldToPopulate = <?= $optionalFields != NULL ? json_encode($optionalFields) : "null" ?>;

function selectRecord(recordId, recordLabel, optionalValue)
{
	opener.document.getElementsByName(formToPopulateName)[0].elements[fieldToPopulateName].value = recordId;
	opener.document.getElementsByName(formToPopulateName)[0].elements[fieldToPopulateLabelName].value = recordLabel;
	if(formToPopulateName !== null && optionalfieldToPopulate !== null && optionalValue !== null)
	{
		for(var k in optionalfieldToPopulate)
		{
			if(optionalValue !== undefined && optionalValue[k] !== undefined)
				opener.document.getElementsByName(formToPopulateName)[0].elements[k].value = optionalValue[k];
			else
				opener.document.getElementsByName(formToPopulateName)[0].elements[k].value = null;
		}
	}
	self.close();
}

function updateTableFromFilters()
{
	var i, j;
	var filter = new Array();
	//FiltersTable
	var filtersNum = document.getElementById("FiltersTable").getElementsByTagName("tr")[1].getElementsByTagName("td").length;
	for(i = 0; i < filtersNum; i++)
		filter.push(document.getElementById("cellfilter_"+i).value.toLowerCase());
	//ContentTable
	var table = document.getElementById("ContentTable");
	var rows = table.getElementsByTagName("tr");
	for(var i = 0; i < rows.length; i++)
	{
		var cells = rows[i].getElementsByTagName("td");
		if(cells.length === 0)
			continue;
		var toHide = false;
		for(var j = 0; j < cells.length; j++)
		{
			var cellText = cells[j].innerHTML;
			if(filter[j] !== "" && cellText.toLowerCase().indexOf(filter[j]) === -1)
			{
				toHide = true;
				break;
			}
		}
		rows[i].style.display = (toHide ? "none" : "");
	}
}

</script>
<p style="margin: 5px 0 5px 20px;"><b>Filtri di ricerca:</b></p>
<div class="table">
	<table class="listing" cellpadding="0" cellspacing="0" id="FiltersTable" >
		<tr>
			<?php

			$colsNum = 0;
			foreach($c->attribNames as $name)
			{
				//vengono mostrati nella lista solo gli attribbuti più importanti
				if(!$c->attribIsImportant[$name])
					continue;
				$colsNum++;
				echo('<th>'.$c->attribLongNames[$name].'</th>');
			}

			?>
		</tr>
		<tr>
			<?php

			$i = 0;
			foreach($c->attribNames as $name)
			{
				//vengono mostrati nella lista solo gli attribbuti più importanti
				if(!$c->attribIsImportant[$name])
					continue;
				echo('<td><input type="text" id="cellfilter_'.$i.'" name="cellfilter_'.$i.'" size="7" onchange="javascript:updateTableFromFilters();" onkeypress="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();" /></th>');
				$i++;
			}

			?>
		</tr>
	</table>
</div>
<div class="table">
	<table class="listing" cellpadding="0" cellspacing="0" id="ContentTable" >
		<tr>
			<?php

			foreach($c->attribNames as $name)
			{
				//vengono mostrati nella lista solo gli attribbuti più importanti
				if(!$c->attribIsImportant[$name])
					continue;
				echo('<th>'.$c->attribLongNames[$name].'</th>');
			}

			?>
		</tr>
		<tr onClick="javascript:selectRecord(null, new Array());" >
			<td></td><td colspan=<?= '"'.($colsNum-1).'"' ?> class="style1" >Nessun valore</td>
		<tr/>
			<?php

			$optionalVal = 'null';
			for($i = 0; $i < count($objsList); $i++)
			{
				if($optionalFields != NULL)
				{
					$optionalVal = array();//'\''.$objsList[$i]->dataTupla[$optionalField].'\'';
					foreach($optionalFields as $fieldToSet => $fieldToGet)
						$optionalVal[$fieldToSet] = $objsList[$i]->dataTupla[$fieldToGet];
				}
				echo '<tr onClick=\'javascript:selectRecord('.($objsList[$i]->dataTupla[STD_ID]).', '.json_encode($objsList[$i]->getLabel(), JSON_HEX_APOS|JSON_HEX_QUOT).', '.(json_encode($optionalVal, JSON_HEX_APOS|JSON_HEX_QUOT)).');\' >'.PHP_EOL;
				foreach($c->attribNames as $name)
				{
					//vengono mostrati nella lista solo gli attribbuti più importanti
					$imp = $c->attribIsImportant[$name];
					if(!$imp)
						continue;
					$style = $imp > 1 ? "class=\"style1\"" : "";
					$tooltip = "";
					if($objsList[$i]->isDataLabelCut($name))
					{
						$objsList[$i]->cutLongStrings(false);
						$tooltip = "title=\"".htmlentities($objsList[$i]->getDataLabel($db,$name),ENT_QUOTES|ENT_IGNORE|ENT_HTML5)."\"";
						$objsList[$i]->cutLongStrings(true);
					}
					echo("<td ".$style." ".$tooltip." >".htmlentities($objsList[$i]->getDataLabel($db,$name),ENT_QUOTES|ENT_IGNORE|ENT_HTML5)."</td>".PHP_EOL);
				}
				echo "</tr>".PHP_EOL;
			}

			?>
	</table>
</div>

		<?php

		}
		
		?>
    </body>
</html>
